﻿package dk.gaming.rummikub.uicomponents
{
	import flash.display.MovieClip;
	import dk.gaming.rummikub.backend.Proxy;
	import dk.gaming.rummikub.events.ProxyEvent;
	import dk.gaming.rummikub.events.GameEvent;
	import flash.events.MouseEvent;
	import dk.gaming.rummikub.Utils.Utility;
	import dk.gaming.rummikub.appcontext.AppContext;
	
	public class GameLister extends MovieClip
	{
		
		private var proxy : Proxy;
		private var gamelist : Array;
		
		private var Container : MovieClip;
		private var RefreshButton : MovieClip;
		private var CreateButton : MovieClip;
		
		private var ScrollPath : MovieClip;
		private var ScrollButton : MovieClip;
		
		public function GameLister()
		{
			Container = containermc;
			ScrollPath = scrollpathmc;
			ScrollButton = scrollbuttonmc;
			ScrollButton.addEventListener(MouseEvent.MOUSE_WHEEL, MouseWheel);
			Refresh();
		}
		
		[Inspectable]
		public var MinButtonHeight : Number = 20;
		
		private function MouseWheel(e:MouseEvent):void
		{
			if(e.delta > 0)
			{
				TweenContainer(Utility.Definite(e.delta), true);
			}
			if(e.delta > 0)
			{
				TweenContainer(Utility.Definite(e.delta), false);
			}
		}
		
		private function TweenContainer(value:Number, direction:Boolean)
		{
			
		}
		
		
		
		private function GameListResponse(e:ProxyEvent):void
		{
			if(e.result == "OK")
			{
				gamelist  = e.gamelist;
				ListGames();
			}
			else
			{
				// TODO : show warning
			}
		}
		
		
		
		private function ProxyError(e:ProxyEvent):void
		{
			
		}
		
		
		private function ListGames():void
		{
			Clear();
			
			var xval : Number = 0;
			
			for(var i : Number = gamelist.length-1; i> 0; i--)
			{
				var gli : GameListItem = gamelist[i] as GameListItem;
				gli.JoinButton.addEventListener(MouseEvent.CLICK, AttemptToJoin);
				gli.x = xval;
				Container.addChild(gli);
				xval += gli.height;
			}
			ScrollButton.y = ScrollPath.y
			var heightval : Number = ScrollPath.height / gamelist.length;
			if(heightval < MinButtonHeight) { heightval = MinButtonHeight; }
			ScrollButton.height = heightval;
		}
		
		private function Clear():void
		{
			while(Container.numChildren >= 0)
			{ Container.removeChildAt(0); }
		}
		
		
		private function Refresh():void
		{
			proxy = new Proxy();
			proxy.addEventListener(ProxyEvent.PROXY_ERROR, ProxyError);
			proxy.addEventListener(ProxyEvent.GAME_LIST_RESPONSE, GameListResponse);
			proxy.GetGameList();
		}
		
		private function AttemptToJoin(e:MouseEvent):void
		{
			proxy.addEventListener(ProxyEvent.JOIN_GAME_REQUEST_RESULT, JoinRequestResult);
			proxy.addEventListener(ProxyEvent.PROXY_ERROR, ProxyError);
			proxy.RequestJoinGame(AppContext.userID, (e.target as GameListItem).ID);
		}
		
		private function JoinRequestResult(e:ProxyEvent):void
		{
			AppContext.CurrentGameID = e.gameID;
			
		}
		
		
		
	}
	
	
	
}